package com.ycsj.goldmedalnewconcept.common.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.MediaPlayerManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.adapter.ClassListAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.common.bean.AnswerUpdate;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.bean.TopicInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;
import com.ycsj.goldmedalnewconcept.common.util.TestTimeCountUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 课文跟读列表详情
 * Created by Administrator on 2019/4/8 0008.
 */

public class AnswerListDetailsActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //LessonId,账号,角色
    private String lessonId, account, role, apptoken;

    // 填充列表的数据源
    private List<AnswerInfo> datas;

    //空视图和列表适配器
    private ClassListAdapter adapter;
    private View emptyView;

    //是否做过跟读的标识
    private String hasdone;

    //计时的ID
    private String rid;

    /**
     * 跳转到当前界面的方法
     *
     * @param context
     * @param lessonId
     */
    public static void goActivity(Context context, String lessonId, String hasdone) {
        Intent it = new Intent(context, AnswerListDetailsActivity.class);
        it.putExtra("lessonid", lessonId);
        it.putExtra("hasdone", hasdone);
        context.startActivity(it);
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_answer_list_details;
    }

    @Override
    protected void init() {

        initStateBar();

        //获取传递对象
        initIntent();

        //初始化标题状态
        initTitle();

        //获取页面数据
        getPageData();

        //请求录音权限
        initPermission();

    }


    /**
     * 申请权限的操作
     */
    private void initPermission() {
        PermissionX.init(this).permissions(Manifest.permission.RECORD_AUDIO).request(new RequestCallback() {
            @Override
            public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                if (allGranted) {
                    //同意了权限
                } else {
                    ToastUtils.showShort("您拒绝了如下权限：" + deniedList + ",录音功能暂时不可使用");
                }
            }
        });
    }


    /**
     * 初始化标题状态
     */
    private void initTitle() {
        tvTitle.setText("课文跟读");
        RelativeLayout.LayoutParams lp = LpUtils.getRelatLp(UiUtils.dp2px(56), UiUtils.dp2px(30));
        lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        lp.addRule(RelativeLayout.CENTER_VERTICAL);
        lp.rightMargin = 8;
        lvEdit.setLayoutParams(lp);
        lvEdit.setVisibility(View.VISIBLE);
        lvEdit.setImageResource(R.drawable.bt_save);
    }

    /**
     * 获取传递数据
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra("lessonid");
        account = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        apptoken = AccountUtils.getToken(this);
        hasdone = getIntent().getStringExtra("hasdone");
    }

    /**
     * 获取页面数据
     */
    public void getPageData() {
        if ("1".equals(hasdone)) {
            //有做过跟读
            http();
        } else {
            //没有做过跟读,从Sp中取数据
            String json = SPUtil.getString(this, lessonId);
            if (!TextUtils.isEmpty(json)) {
                datas = GsonUtil.jsonToList(json, AnswerInfo[].class);
                rlLoading.setVisibility(View.GONE);
                //设置列表的数据
                setRvData();
            }
        }
    }

    /**
     * 有成绩时从服务器获取数据
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("acc", account);
        map.put("role", role);
        map.put("done", "1");
        map.put("lessonid", lessonId);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");

        HttpUtils.get(HttpAddress.KWGDLIST, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                rlLoading.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                rlLoading.setVisibility(View.GONE);
                TopicInfo info = null;

                datas = new ArrayList<>();
                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, TopicInfo.class);
                    } catch (Exception e) {
                        LogUtils.iTag("test", Constants.PARSEDATAERROR);
                    }
                }

                if (null != info) {

                    //取出所有问题的数据集合
                    List<TopicInfo.QuestionListBean> questions = info.getQuestion_list();
                    if (null != questions && questions.size() != 0) {
                        for (int i = 0; i < questions.size(); i++) {
                            AnswerInfo answerInfo = new AnswerInfo();
                            answerInfo.audioPath = "";
                            answerInfo.path = questions.get(i).getAudio();
                            answerInfo.questionContent = questions.get(i).getDialogue();
                            answerInfo.score = Float.parseFloat(questions.get(i).getQuestion_score());
                            answerInfo.isShowScore = true;
                            answerInfo.question_id = questions.get(i).getQuestion_id();
                            answerInfo.question_type = questions.get(i).getQuestion_type();
                            datas.add(answerInfo);
                        }

                        //设置列表的数据
                        setRvData();

                    } else {
                        LogUtils.iTag("test", Constants.EMPTY);
                    }

                } else {
                    LogUtils.iTag("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 设置列表的数据
     */
    private void setRvData() {
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view_white_bg, null);
        adapter = new ClassListAdapter(this, R.layout.item_lv_answer_list, datas);
        BqaManager.setRv(emptyView, this, adapter, rv);
        adapter.setListener(new ClassListAdapter.onRecordListener() {
            @Override
            public void onRecord() {
                //如果有重新录音则需要重新上传
                lvEdit.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.lv_edit:
                //上传成绩的操作
                doCommitAction();
                break;
        }
    }

    /**
     * 上传成绩的接口
     */
    private void doCommitAction() {

        CustomDialogManager.show(this, "提交中...");

        // 创建上传的数据集合
        List<AnswerUpdate> updatas = new ArrayList<>();

        // 计算总分数
        float score = 0;
        for (int i = 0; i < datas.size(); i++) {
            score += datas.get(i).score;
            AnswerUpdate info = new AnswerUpdate();
            info.question_id = datas.get(i).question_id;
            info.question_type = datas.get(i).question_type;
            info.question_score = datas.get(i).score + "";
            updatas.add(info);
        }

        //平均分
        score = score / datas.size();


        // 生成上传的Json字符串
        String passJson = GsonUtil.listToJson(updatas);

        Map<String, String> map = new HashMap<>();
        map.put("type", "11");
        map.put("acc", account);
        map.put("role", role);
        map.put("lessonid", lessonId);
        map.put("total_time", "0");
        map.put("score", score + "");
        map.put("question_list", passJson);
        map.put("apptoken", apptoken);
        map.put("platform", "2");
        map.put("schoolid", AccountUtils.getSchoolId(this));
        if ("2".equals(role)) {
            map.put("classnum", AccountUtils.getTeacherClass(this));
            map.put("teacherid", AccountUtils.getAccount(this));
        } else if ("0".equals(role)) {
            map.put("classnum", AccountUtils.getClassNum(this));
            map.put("teacherid", AccountUtils.getTeacher(this));
        }

//        LogUtils.iTag("test", HttpAddress.COMMITKWGD + "?type=11&acc=" + account + "&role=" + role +
//                "&lessonid=" + lessonId + "&total_time=0&score=" + score + "&question_list=" + passJson + "&apptoken=" +
//                apptoken + "&platform=2&schoolid=" + AccountUtils.getSchoolId(this) +
//                "&classnum=" + AccountUtils.getClassNum(this) + "&teacherid=" + AccountUtils.getTeacher(this)
//        );

        HttpUtils.post(HttpAddress.COMMITKWGD, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();

                if (!TextUtils.isEmpty(response)) {
//                    LogUtils.iTag("test", "提交结果是:" + response);
                    ResultInfo info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    if ("200".equals(info.getState())) {
                        ToastUtils.showShort("提交成功");

                        //通知FollowReadDetailsActivity界面关闭
                        BusInfo busInfo = new BusInfo();
                        busInfo.type = FollowReadDetailsActivity.FINISH;
                        EventBus.getDefault().post(busInfo);
                        finish();

                    } else {
                        StateCodeUtils.showSateCode(info.getState());
                    }
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        TestTimeCountUtil.startTime(this, "9", String.valueOf(lessonId).substring(0, 4), lessonId, new TestTimeCountUtil.onSuccessListener() {
            @Override
            public void onSuccess(String infoRid) {
                rid = infoRid;
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        TestTimeCountUtil.stopTime(this, rid);
    }

    /**
     * 生命周期解绑
     */
    @Override
    protected void onDestroy() {
        MediaPlayerManager.getInstance().stop();
        super.onDestroy();
    }
}
